package org.agile2soft.nexoma.tapestry.services.security;

import org.springframework.dao.DataAccessException;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.providers.dao.SaltSource;
import org.springframework.security.providers.encoding.PasswordEncoder;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;

public class MyUserDetailsService implements UserDetailsService {

    private MyUserDetailsImpl _user;
    private MyUserDetailsImpl _admin;

    public MyUserDetailsService( PasswordEncoder encoder, SaltSource salt) {
        GrantedAuthority user = new GrantedAuthorityImpl( "ROLE_USER" );

        _user = new MyUserDetailsImpl( "user" );
        _user.addAuthority( user );
        _user.setPassword( encoder.encodePassword( "user", salt.getSalt( _user ) ) );

        _admin = new MyUserDetailsImpl( "admin");
        _admin.addAuthority( user );
        _admin.addAuthority( new GrantedAuthorityImpl( "ROLE_ADMIN" ) );
        _admin.setPassword( encoder.encodePassword( "admin", salt.getSalt( _admin ) ) );
    }

	public UserDetails loadUserByUsername( String name ) throws UsernameNotFoundException,DataAccessException {
        if ( "user".equals( name ) ) { 
        	return _user;
        }
        if ( "admin".equals( name ) ) { 
        	return _admin;
        }
        throw new UsernameNotFoundException(name);
    }

}

